#coding: utf-8

import config
from data_feed import DataFeed
from utils.mysql_util import MySQLUtil

import sys
reload(sys)
sys.setdefaultencoding("UTF-8")

class DataFeedDAO(object):
    DATA_FEED_TABLE = "data_feed_table"

    def __init__(self):
        self._db = MySQLUtil()

    def close(self):
        self._db.close()

    def save_or_update(self, data_feed):
        sql = "replace into %s(`file_name`, `md5_value`, `last_modified`, `file_size`) " \
              "values ('%s', '%s', '%s', '%s')" % (
                self.DATA_FEED_TABLE,
                data_feed._file_name,
                data_feed._md5_value,
                data_feed._last_modified,
                data_feed._size)

        return self._db.save_or_update(sql)

    def delete(self, file_name):
        sql = """delete from %s where file_name='%s'""" % (
                self.DATA_FEED_TABLE, file_name)

        return self._db.delete(sql)

    def select(self, file_name):
        sql = """select * from %s where file_name='%s'""" % (
                self.DATA_FEED_TABLE,
                file_name)

        rows = self._db.select(sql)
        if len(rows) == 0:
            return None
        else:
            info = rows[0]
            data_feed = DataFeed()
            data_feed._file_name = info[0]
            data_feed._md5_value = info[1]
            data_feed._last_modified = info[2]
            data_feed._size = long(info[3])

            return data_feed
